package com.lg.wechat.business.oauth.service.impl;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lg.wechat.business.oauth.service.WxOauthService;
import com.lg.wechat.business.wxuser.entity.WxUser;
import com.lg.wechat.business.wxuser.service.WxUserService;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Service
public class WxOauthServiceImpl implements WxOauthService{

	@Autowired
	private WxMpService wxMpService;
	
	@Autowired
	private WxUserService wxUserService;
	
	@Override
	public WxUser oauthSave(String code) throws WxErrorException {
		  WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		  boolean valid = wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
		  if(!valid){
			  wxMpOAuth2AccessToken = wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
		  }
		  WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		  if(wxMpUser!=null){
			  boolean flag=true;
			  WxUser wxUser=wxUserService.selectByOpenId(wxMpUser.getOpenId());
			  if(wxUser==null){
				  flag=false;
				  wxUser=new WxUser();
			  }
		      try {
				BeanUtils.copyProperties(wxUser, wxMpUser);
			  } catch (Exception e) {
				e.printStackTrace();
			  }
		      if(flag){
		    	  wxUserService.update(wxUser);
		      }else{
		    	  wxUserService.insert(wxUser); 
		      }
			  return wxUser;
		  }
		  return null;
	}

}
